package com.wva.common.utils;

import com.wva.common.exception.BusinessException;
import com.wva.common.exception.SystemException;
import com.wva.common.status.Bind;
import com.wva.common.status.StatusEnum;
import com.wva.common.status.StatusImpl;
import lombok.extern.slf4j.Slf4j;

import javax.validation.*;
import java.util.Set;

/**
 * 参数校验工具类
 * @Author: hong
 * @Date: 2025/2/2 00:09:31
 */
@Slf4j
public class ValidateUtils {
    static Validator validator;

    /**
     * 调用Hibernate Validation校验一个对象
     * 失败抛出异常
     * @param object
     * @param groups
     * @param <T>
     */
    public static <T> void validate(T object, Class<?>... groups) {
        if (validator == null) {
            //创建工厂
            try {
                try (ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory()) {
                    //获得一个校验器
                    validator = validatorFactory.getValidator();
                }
            } catch (Exception e) {
                log.error("校验器validator获取失败");
                throw new SystemException(StatusEnum.INTERNAL_ERROR);
            }
        }

        //校验一个对象，可变参数传入分组接口
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object, groups);

        //遍历校验结果
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            //从payload取出status
            Set<Class<? extends Payload>> payloads = constraintViolation.getConstraintDescriptor().getPayload();
            for (Class<? extends Payload> payload : payloads) {
                Bind bind = payload.getAnnotation(Bind.class);
                if (bind != null) {
                    throw new BusinessException(bind.status());
                }
            }

            //常规抛出
            StatusImpl status = new StatusImpl();
            status.setCode(StatusEnum.PARAMS_CHECK_FAIL.getCode());
            status.setMessage(constraintViolation.getMessage());
            throw new BusinessException(status);
        }
    }

    // public static void sortErrors(List<ObjectError> allErrors) {
    //     allErrors.sort(new Comparator<ObjectError>() {
    //         @Override
    //         public int compare(ObjectError o1, ObjectError o2) {
    //
    //             ConstraintViolation constraintViolation1 = o1.unwrap(ConstraintViolation.class);
    //             ConstraintViolation constraintViolation2 = o2.unwrap(ConstraintViolation.class);
    //
    //             List<> constraintValidatorClasses = constraintViolation1.getConstraintDescriptor()
    //                     .getConstraintValidatorClasses();
    //
    //
    //         }
    //     });
    // }
}
